package io.wins.vertx.utils;

import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.wins.vertx.database.JdbcExecutor;
import io.wins.vertx.entity.Image;

public class ImageHelper {
    private Vertx vertx;

    public static ImageHelper create(final Vertx vertx) {
        final ImageHelper helper = new ImageHelper();
        helper.vertx = vertx;
        return helper;
    }

    private ImageHelper() {
    }

    public void SaveImage(final Image image) {
        final Future future = Future.future();
        final JsonObject sqlMes = new JsonObject()
            .put("action", "insert")
            .put("sql", "INSERT into ds_image (id, image_path, image_base, created_on) VALUES(?,?,?,?)")
            .put("params", new JsonArray()
                .add(image.getId())
                .add(image.getImagePath())
                .add(image.getImageBase())
                .add(image.getCreatedOn()));
        this.vertx.eventBus().send(JdbcExecutor.CONSUMER, sqlMes, future.completer());
    }

    public void LoadImage(final String id, final Handler<AsyncResult<Message<JsonArray>>> done) {
        final JsonObject sqlMes = new JsonObject()
            .put("action", "select")
            .put("sql", "select * from ds_image where id = ?")
            .put("params", new JsonArray().add(id));
        this.vertx.eventBus().send(JdbcExecutor.CONSUMER, sqlMes, done);
    }

    public void ListImage(final JsonArray ids, final Handler<AsyncResult<Message<JsonArray>>> done) {
        final JsonObject sqlMes = new JsonObject()
            .put("action", "select")
            .put("sql", this.buildSql(ids.size()))
            .put("params", ids);
        this.vertx.eventBus().send(JdbcExecutor.CONSUMER, sqlMes, done);
    }

    private String buildSql(final int size) {
        final StringBuilder sb = new StringBuilder();
        sb.append("select * from ds_image where id in (");
        int i = 0;
        while (i < size) {
            sb.append("?,");
            i++;
        }
        sb.deleteCharAt(sb.length() - 1).append(')');
        return sb.toString();
    }
}
